#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

#define in read()
#define pii pair<int,int>
#define fi first
#define se second
#define mes(x) memset(x,0,sizeof(x))
#define FILE(x) freopen(x".in","r",stdin);\
	freopen(x".out","w",stdout)

int read(){
	int x = 0,sgn = 1;char ch = getchar();
	for(;!isdigit(ch);ch = getchar()) if(ch == '-') sgn = -1;
	for(;isdigit(ch);ch = getchar()) x = (x<<1)+(x<<3)+(ch^48);
	return x*sgn;
}

const int MAXN = 1e5+10;
const int inf = 0x3f3f3f3f;

int n,m,h[MAXN],cnt,d[MAXN];
bool v[MAXN];
set<int>s[MAXN];
struct edge{int v,w,nxt;}e[MAXN<<2];
void link(int x,int y,int c){e[++cnt] = (edge){y,c,h[x]};h[x] = cnt;}

void dijk(int S){
	memset(d,0x3f,sizeof(d)); d[S] = 0;
	priority_queue<pii> q;q.push(pii(0,S));
	while(q.size()){
		int x = q.top().se;q.pop();
		if(v[x]) continue;v[x] = 1;
		for(int i = h[x];i;i = e[i].nxt){
			int y = e[i].v; int w = s[x].find(e[i].w) == s[x].end();
			if(d[y] > d[x] + w) d[y] = d[x] + w,s[y].clear();
			if(d[y] == d[x] + w) {
				if(s[y].find(e[i].w) == s[y].end()) s[y].insert(e[i].w);
				q.push(pii(-d[y],y));
			}
		}
	}
}

int main (){
	n = in,m = in;
	for(int i = 1;i <= m;i++){
		int x = in,y = in,c = in;
		link(x,y,c);link(y,x,c);
	}
	dijk(1);
	printf("%d\n",d[n] == inf ? -1 : d[n]);
	return 0;
}

